#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <stdio.h>

char** string_split(char* str, char d, int* numOfTokens) {
    const char delimiter[] = {d, '\\0'};
    char* token = strtok(str, delimiter);
    int capacity = 10;
    char** tokens = malloc(capacity * sizeof(char*));
    int count = 0;

    while (token != NULL) {
        if (count >= capacity) {
            capacity *= 2;
            tokens = realloc(tokens, capacity * sizeof(char*));
        }
        tokens[count++] = token;
        token = strtok(NULL, delimiter);
    }
    *numOfTokens = count;
    return tokens;
}

int main(int argc, char *argv[]) {
    if (argc < 4) {
        printf("Usage: %s [-m|-u] local_mount_point username:password@webdav_address\\n", argv[0]);
        return 1;
    }

    char* command = argv[1];
    char* localMountPoint = argv[2];
    char* webdavURL = argv[3];

    int numOfTokens;
    char** tokens = string_split(webdavURL, '@', &numOfTokens);
    if (numOfTokens != 2) {
        printf("Invalid WebDAV URL format. Expected username:password@webdav_address\\n");
        free(tokens);
        return 1;
    }

    char* credentials = tokens[0];
    webdavURL = tokens[1];

    char** credentialsTokens = string_split(credentials, ':', &numOfTokens);
    if (numOfTokens != 2) {
        printf("Invalid credentials format. Expected username:password\\n");
        free(tokens);
        free(credentialsTokens);
        return 1;
    }

    char* username = credentialsTokens[0];
    char* password = credentialsTokens[1];

    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        free(tokens);
        free(credentialsTokens);
        return 1;
    } else if (pid == 0) {
        // 子进程执行挂载或卸载命令
        if (strcmp(command, "-m") == 0) {
            setenv("DAV_USER", username, 1);
            setenv("DAV_PASS", password, 1);
            execlp("mount", "mount", "-t", "davfs", webdavURL, localMountPoint, NULL);
        } else if (strcmp(command, "-u") == 0) {
            execlp("umount", "umount", localMountPoint, NULL);
        } else {
            printf("Invalid command: %s\\n", command);
            return 1;
        }
    } else {
        // 等待子进程结束
        int status;
        waitpid(pid, &status, 0);
        if (WIFEXITED(status)) {
            int exitStatus = WEXITSTATUS(status);
            if (exitStatus == 0) {
                printf("Command executed successfully.\\n");
            } else {
                printf("Command failed with exit status: %d\\n", exitStatus);
            }
        } else {
            printf("Command terminated abnormally.\\n");
        }
    }

    free(tokens);
    free(credentialsTokens);
    return 0;
}
